package com.yunkaweilai.android.activity.operation.Message;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.CaptureActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.fragment.member.CommonMemberFragmentMessageMember;
import com.yunkaweilai.android.model.jici.CommonMemberModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.member.MemberLevelModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 选择群发会员
 * Created by Administrator on 2017/7/31.
 */

public class CommonGroupMemberActivity extends BaseActivity {

    @BindView(R.id.id_listView_search)
    ListView idListView;
    @BindView(R.id.id_edt_search)
    EditText idEdtSearch;
    @BindView(R.id.id_img_clean)
    ImageView idImgClean;
    @BindView(R.id.id_img_qr_code)
    ImageView idImgQrCode;
    @BindView(R.id.config_hidden)
    TextView mTextViewhidden;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.line_search)
    LinearLayout Linesearch;
    private int mpage = 1;
    private int mpage1 = 1;
    private boolean mHasMore = true;
    private ArrayList<MemberHeadModel> memberList = new ArrayList<>();
    private ArrayList<MemberLevelModel.DataBean.ListBean> list = new ArrayList<>();
    private CommonAdapter<MemberHeadModel> adapter;
    private Gson gson = new Gson();
    private String keywords = "";
    public static List<String> IdList = new ArrayList<>();//存储选中人id的list
    @BindView(R.id.id_tabLayout)
    TabLayout idTabLayout;
    @BindView(R.id.id_viewPager)
    ViewPager idViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_member);
        ButterKnife.bind(this);
        mTextViewhidden.requestFocus();//获取焦点，防止弹出软键盘（不过好像因为在edittext上面，所以自动获取了焦点，不需要这句话）
        new TitleBuilder(mAc).setTitleText("选择会员").setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        InputMethodUtils.closeSoftKeyboard(mAc);
                        finish();
                    }
                }).setRightText("确定").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = "";
                for (int i = 0; i < IdList.size(); i++) {
                    if (i == IdList.size() - 1) {
                        s = s + IdList.get(i);
                    } else {
                        s = s + IdList.get(i) + ",";
                    }
                }
                String num = "" + IdList.size();
                Intent intent = new Intent();
                intent.putExtra("IdList", s);
                intent.putExtra("IdListNum", num);
                setResult(RESULT_OK, intent);
                InputMethodUtils.closeSoftKeyboard(mAc);
                finish();
            }
        });
        initAdapter();
        initClick();
        initView();
    }

    private void initView() {
        /**
         * 获取会员等级
         */
        HttpRequest.postUrl(Api.MEMBER_LEVEL_LIST)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        dismissProgressDialog();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            MemberLevelModel memberLevelModel = gson.fromJson(json, MemberLevelModel.class);
                            list.clear();
                            MemberLevelModel.DataBean.ListBean listBean = new MemberLevelModel.DataBean.ListBean();
                            listBean.setId("0");
                            listBean.setLevel_name("全部");
                            list.add(listBean);
                            list.addAll(memberLevelModel.getData().getList());
                            CommonMemberAdapter adapter = new CommonMemberAdapter(getSupportFragmentManager(), list);
                            idViewPager.setAdapter(adapter);
                            idTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                            idTabLayout.setupWithViewPager(idViewPager);
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });
    }

    private void initClick() {
        //搜索框
        idEdtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null && idEdtSearch.length() > 0) {
                    //点击搜索要做的操作
                    keywords = idEdtSearch.getText().toString();
                    InputMethodUtils.closeSoftKeyboard(mAc);
                    initHttp(keywords);
                } else {
                    hideSearch(false);
                    InputMethodUtils.closeSoftKeyboard(mAc);
                }
                return false;
            }
        });

        idEdtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    idImgClean.setVisibility(View.GONE);
                    return;
                } else {
                    idImgClean.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    private void initAdapter() {
        adapter = new CommonAdapter<MemberHeadModel>(mAc, R.layout.item_list_member_for_group, memberList) {
            @Override
            protected void convert(ViewHolder viewHolder, final MemberHeadModel item, int position) {
                ImageView idImgHead = viewHolder.getView(R.id.id_img_head);
                Utils.MemberHeadImg(mAc, item.getMember_avatar(), item.getMember_sex(), idImgHead);
                TextView idTvName = viewHolder.getView(R.id.id_tv_name);

                //设置名字、手机和状态
                if (item.getStatusStr().equals("过期")) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='" + getResources().getColor(R.color.calu_red) + "'>" + "已过期" + "</font>");
                } else if ("2".equals(item.getMl_status())) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='" + getResources().getColor(R.color.calu_red) + "'>" + "已锁定" + "</font>");
                } else if ("3".equals(item.getMl_status())) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='" + getResources().getColor(R.color.calu_red) + "'>" + "已挂失" + "</font>");
                } else {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName);
                }

                viewHolder.setText(R.id.id_tv_level, "等级：" + item.getLevel_name() + "     卡号：" + item.getCard_no());
                viewHolder.setText(R.id.id_tv_discount, "折扣：" + item.getDiscount() / 10 + "折   积分：" + item.getMember_points() + "   余额：" + item.getMember_price());

                //设置checkbox 来回切换的时候记录
                final CheckBox checkBox = viewHolder.getView(R.id.item_list_rbtn);
                final LinearLayout linearLayout = viewHolder.getView(R.id.line_item_checkbox);
                checkBox.setChecked(false);
                for (int i = 0; i < IdList.size(); i++) {
                    if (item.getId().equals(IdList.get(i))) {
                        checkBox.setChecked(true);
                    }
                }
                checkBox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (checkBox.isChecked()) {
                            IdList.add(item.getId());
                        } else {
                            decList(item.getId(), IdList);
                        }
                    }
                });
                linearLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        checkBox.performClick();
                    }
                });
//                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                    @Override
//                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                        if (b){
//                            IdList.add(item.getId());
//                        }
//                        else {
//                            decList(item.getId(),IdList);
//                        }
//                    }
//                });

            }
        };
        idListView.setAdapter(adapter);
    }

    //减去list中的某一个数值
    private List<String> decList(String s, List<String> list) {
        for (int j = 0; j < list.size(); j++) {
            if (s.equals(list.get(j))) {
                list.remove(j);
                return list;
            }
        }
        return list;
    }

    //会员列表正常
    private void initHttp(String keyword) {
        HttpRequest.postUrl(Api.MEMBER_COMMON_LIST)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("keyword", keyword)
                .addParams("filter_member_tel", "1")
                .addParams("CurrPage", mpage + "")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc, json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            CommonMemberModel CommonMemberModel = gson.fromJson(json, CommonMemberModel.class);
                            memberList.clear();
                            memberList.addAll(CommonMemberModel.getData().getList());
                            if (memberList.size() > 0) {
                                hideSearch(true);
                            } else {
                                showToast("该会员不存在");
                            }
                        } else {
                            showToast("服务器出错");
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    private void hideSearch(boolean hideMutiple) {
        if (hideMutiple) {
            multipleStatusView.setVisibility(View.GONE);
            Linesearch.setVisibility(View.VISIBLE);
        } else {
            multipleStatusView.setVisibility(View.VISIBLE);
            Linesearch.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.id_img_clean, R.id.id_img_qr_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_img_clean:
                idImgClean.setVisibility(View.GONE);
                idEdtSearch.setText("");
                keywords = "";
                memberList.clear();
                adapter.notifyDataSetChanged();
                hideSearch(false);
                break;
            case R.id.id_img_qr_code:
                getCameraManifest();
                break;
        }
    }


    public static final int SHOP_QR_CODE = 333;
    //获取照相机权限
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private void getCameraManifest() {
        MPermissions.requestPermissions(this, MY_PERMISSIONS_REQUEST_CAMERA, Manifest.permission.CAMERA);
    }

    private void getCamera() {
        Intent intent = new Intent(mAc, CaptureActivity.class);
        startActivityForResult(intent, SHOP_QR_CODE);
    }

    @PermissionGrant(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestSuccess() {
        getCamera();
    }

    @PermissionDenied(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestError() {
        showToast("授权失败！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 333:
                    //处理扫描结果（在界面上显示）
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        String result = bundle.getString(CaptureActivity.RESULT);
                        idEdtSearch.setText(result);
                        initHttp(result);
                    }
                    break;
            }
        }
    }
    class CommonMemberAdapter extends FragmentPagerAdapter {
        private List<MemberLevelModel.DataBean.ListBean> list;

        public CommonMemberAdapter(FragmentManager fm, List<MemberLevelModel.DataBean.ListBean> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return list.get(position).getLevel_name();
        }

        //todo:k 新建step4
        @Override
        public Fragment getItem(int position) {
            Fragment fragment = new Fragment();
            fragment = CommonMemberFragmentMessageMember.getInstentce(list.get(position).getId());
            return fragment;
        }

        @Override
        public int getCount() {
            return list.size();
        }

    }

}
